package com.safe.ocs.controls;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.hibernate.Query;
import org.hibernate.Session;

import com.safe.ocs.beans.InputSMS;
import com.safe.ocs.beans.OMsgPageBean;
import com.safe.ocs.beans.OutputSMS;
import com.safe.ocs.services.CViewMsg;
import com.safe.ocs.services.ViewMsg;
import com.safe.ocs.utils.HibernateUtil;

public class MessageView extends DispatchAction{

	public ActionForward find(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		response.setContentType("text ml;charset=utf-8");
		PrintWriter out = response.getWriter();
		if(request.getParameter("mv_sendernum")!=null||request.getParameter("mv_senderstaut")!=null)
		{
			int start = Integer.parseInt(request.getParameter("start"));
			int limit = Integer.parseInt(request.getParameter("limit"));
			
			
			int n=0;
			List<OutputSMS> list=new ArrayList<OutputSMS>();
			boolean sendedStaut=false;
			String telNo=request.getParameter("mv_sendernum");
			String staut=request.getParameter("mv_senderstaut");
			if(staut.equals("已发送"))
				sendedStaut=true;
			
			
			OutputSMS outputBean=new OutputSMS();
			outputBean.setTelNo(telNo);
			outputBean.setSendedStaut(sendedStaut);
			
			Session session = HibernateUtil.getSession();
			
			Query query;
			StringBuilder sb=new StringBuilder();
			sb.append("from OutputSMS as ops where 1=1");
			if(!telNo.equals("")&&telNo!=null)
			{
				sb.append(" and ops.telNo=?");
			}
			if(!staut.equals("")&&staut!=null)
			{
				sb.append(" and ops.sendedStaut=?");
			}
			
			
			query=session.createQuery(sb.toString()); 
			
			
			if(!telNo.equals("")&&telNo!=null)
			{
				query=query.setParameter(n,telNo);
				n++;
			}
			if(!staut.equals("")&&staut!=null)
			{
				query=query.setParameter(n,sendedStaut);
				n++;
			}
			
			int totalProperty = query.list().size();
			list=query.setFirstResult(start).setMaxResults(limit).list();
			
			OMsgPageBean bean = new OMsgPageBean(totalProperty,list);
			JSONObject result = JSONObject.fromObject(bean);
			String show=result.toString();
			out.println(show);
		}
		else
		{
			int start = Integer.parseInt(request.getParameter("start"));
			int limit = Integer.parseInt(request.getParameter("limit"));
			
			
			String test = new CViewMsg().findMessage(start,limit);
			out.println(test);
		}
		return null;
	}
	
	
	 

}


